﻿

namespace Common.Algorithm.Core.LocalTest;

/// <summary>
///  CommonGeneticExecute.Run(GraphGenerator.GenCityGraph(cityFile, 70));
///  CommonGeneticExecute.RunMany(GraphGenerator.GenCityGraph(cityFile, 70), 10);
///  CommonGeneticExecute.Execute();
/// </summary>
public class SimpleGeneticTSPExecute
{
    static string assemblyPath = Assembly.GetExecutingAssembly().Location;
    static string assemblyDir = Path.GetDirectoryName(assemblyPath) + "\\";
    
     
    public static IList<int> Run(IEnumerable<GraphEdge> edges)
    {
        SimpleGeneticTSPService genetic = new SimpleGeneticTSPService(edges);
        Action action = () =>
        {
            genetic.RunAlgm(500);
        };
        Console.WriteLine($"time:{TimeService.TimeWatch(action)}");

        Console.WriteLine($"{string.Join("\n", genetic.bestPath)}");
        Console.WriteLine($"{string.Join("\n", SimpleGeneticTSPService.PathLength(genetic.bestPath.ToArray()))}");
        return genetic.bestPath;
    }

    /// <summary>
    /// 多次测试
    /// </summary>
    /// <param name="edges"></param>
    /// <param name="count"></param>
    public static void RunMany(IEnumerable<GraphEdge> edges, int count)
    {
        double shortDist = double.MaxValue;

        List<int[]> paths = new List<int[]>();

        Parallel.For(0, count,
            (item) =>
            {
                var finalPath = Run(edges).ToArray();
                paths.Add(finalPath);
            }
            );

        var bestPath = paths.OrderBy(p => SimpleGeneticTSPService.PathLength(p)).First();
        Console.WriteLine($"BEST-DIST==={bestPath}");
    }

    public static void Execute()
    {
        string cityFile = @$"{assemblyDir}\_data_\pr76.txt";
        Run(GraphGenerator.GenCityGraph(cityFile, 70));
        RunMany(GraphGenerator.GenCityGraph(cityFile, 70), 10);
    }
     
}
